package com.gopay.bis.service.bank.impl.bcdl;
import java.util.Map;

import javax.annotation.Resource;

import com.gopay.common.domain.bank.abc.bcdl.quyeryCQRA10.res.ApResCQRA10;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.bis.common.util.SendSmsUtils;
import com.gopay.bis.manager.bank.bcdl.AbcBcdlManager;
import com.gopay.common.constants.bank.AbcConstants;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BcdlMessage;
import com.gopay.common.domain.bank.BcdlResult;
import com.gopay.common.domain.bank.abc.bcdl.bal.res.ApQueryBalRes;
import com.gopay.common.domain.bank.abc.bcdl.query.res.ApQueryRes;
import com.gopay.common.domain.bank.abc.bcdl.res.NewApRes;
import com.gopay.common.domain.bank.bcdl.BcdlPacket;
import com.gopay.common.domain.bank.bcdl.BcdlPacketRes;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BcdlInteractRemoteService;

import org.springframework.stereotype.Service;

/**
 * 农行银企直连实现
 * 
 * @AbcBcdlServiceImpl.java
 * @author lilili
 */
public class AbcBcdlServiceImpl extends BaseBcdlServiceImpl implements BcdlInteractRemoteService {
	
	private static Logger logger = LoggerFactory.getLogger(AbcBcdlServiceImpl.class);
	
	@Resource(name = "abcBcdlManager")
	AbcBcdlManager abcBcdlManager;
	@Resource(name = "smsConfig")
	private Map<String, String> smsConfig;
	
	@Override
	public BcdlResult eft(BcdlMessage base) {
		BcdlResult result = new BcdlResult();
		try {
			BcdlMessage message = (BcdlMessage) base;
	            if (message.getDcblType() == BankConstants.DCBL_CORP) {
	                // 对公
	            	NewApRes res = abcBcdlManager.payCorp(message);
	                result.setDefaultModel(res);
	                
	                if(AbcConstants.ABC_RESCODE_SUCCESS.equals(res.getRespCode())){
	                	// 银行请求成功
	                	result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
	                	result.setSuccess(true);
	                }else {
	                	//add by zyt,2017-10-20,返回信息无此字段，设置进去
						res.setTransCode("CFRT02");
						result.setNeedRefund(isNeedRefund(res, base.getOrderId()));
						if(result.isNeedRefund()){
							result.setBankRetCode(res.getRespCode());
		                	//  农行ERP应答错误报文返回码或者农行ERP应答错误报文返回来源
		    				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
		    				result.setErrorMsg(res.getRespInfo());
		    				result.setSuccess(false);
						}else{
							result.setBankRetCode(res.getRespCode());
							result.setErrorMsg(res.getRespInfo());
							result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
		    				result.setSuccess(false);
						}
	    			}
	            } else if (message.getDcblType() == BankConstants.DCBL_PERSON) {
	                // 对私
	            	NewApRes res = abcBcdlManager.payPerson(message);
	                result.setDefaultModel(res);
	                
	                if(AbcConstants.ABC_RESCODE_SUCCESS.equals(res.getRespCode())){
	                	// 银行请求成功
	                	result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
	                	result.setSuccess(true);
	                }else {
	    				//add by zyt,2017-10-20,返回信息无此字段，设置进去
						res.setTransCode("CFRT21");
						result.setNeedRefund(isNeedRefund(res, base.getOrderId()));
						if(result.isNeedRefund()){
							result.setBankRetCode(res.getRespCode());
		                	//  农行ERP应答错误报文返回码或者农行ERP应答错误报文返回来源
		    				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
		    				result.setErrorMsg(res.getRespInfo());
		    				result.setSuccess(false);
						}else{
							result.setBankRetCode(res.getRespCode());
							result.setErrorMsg(res.getRespInfo());
							result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
		    				result.setSuccess(false);
		    				
						}
	    			}
	            }  else {
	                result.setResultCode("AbcBcdlServiceImpl.process:not match");
	                return result;
	            }
		} catch (GopayException e) {
			if(ProcCodeConstants.PROC_CODE_100E6047.equals(e.getErrCode())){
				String custName = getCustName(base.getOrderId());
				SendSmsUtils.sendSms(base.getGopayBankOrderNo(), smsConfig.get("switch"), "ABC",smsConfig.get("mobile"),e.getErrMsg()
						+",商户名称："+custName+",金额："+base.getAmount().toString());
			}
			logger.error("ABC银企直连异常 eft", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception ex){
			logger.error("ABC银企直连异常 eft error", ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public BcdlResult query(BcdlMessage base) {
		BcdlResult result = new BcdlResult();
		try {
			BcdlMessage message = (BcdlMessage) base;
			message.setDcblType(BankConstants.DCBL_QUERY);
                // 查询
                ApQueryRes res = abcBcdlManager.payQuery(message);
                result.setDefaultModel(res);
            	String respPrvData = res.getCmp().getRespPrvData();
    			String respCode = respPrvData.substring(respPrvData.length()-8);
    			String szRespCode = respCode.substring(0, 4);
    			
                if(AbcConstants.ABC_RESCODE_SUCCESS.equals(res.getRespCode()) && AbcConstants.ABC_RESCODE_SUCCESS.equals(szRespCode)){
                	// 银行请求成功
                	result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
                	result.setSuccess(true);
                }else {
                	//add by zyt,2017-9-25，根据返回报文，设置是否失败，且需要做拒绝账务，查询报文都成功，所以不对success做判断
        			//add by zyt,2017-10-20,返回信息无此字段，设置进去
        			res.setTransCode("CQRT04");
        			result.setNeedRefund(isNeedRefund(res, base.getOrderId()));
        			
        			if(result.isNeedRefund()){
                    	//  农行ERP应答错误报文返回码或者农行ERP应答错误报文返回来源
        				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
        				result.setSuccess(false);
        			}else{
	    				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
	    				result.setSuccess(false);
        			}
        			
        			if(!AbcConstants.ABC_RESCODE_SUCCESS.equals(res.getRespCode())){
	        			result.setBankRetCode(res.getRespCode());
	        			result.setErrorMsg(res.getRespInfo());
        			}else{
        				result.setBankRetCode(szRespCode);
	        			result.setErrorMsg(szRespCode);
        			}
    			}
                
			return result;
		} catch (GopayException e) {
			logger.error("ABC银企直连异常 query", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception ex){
			logger.error("ABC银企直连异常 query error", ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	
	@Override
	public BcdlResult queryBalance(BcdlMessage base) {
		BcdlResult result = new BcdlResult();
		try {
			BcdlMessage message = (BcdlMessage) base;
			message.setDcblType(BankConstants.DCBL_QUERYBAL);
                // 查询账户余额
                ApQueryBalRes res = abcBcdlManager.queryBal(message);
                result.setDefaultModel(res);
                if(AbcConstants.ABC_RESCODE_SUCCESS.equals(res.getRespCode())){
                	// 银行请求成功
                	result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
                	result.setSuccess(true);
                	result.setModel("payAccNum", res.getPayAccNum());
                    result.setModel("balance", res.getBalance());
                }else if(!AbcConstants.ABC_ERP_ERR_RES_RESP_CODE.equals("") && 
                		!AbcConstants.ABC_RESCODE_SUCCESS.equals(res.getRespCode())){
                	result.setBankRetCode(res.getRespCode());
                	//  农行ERP应答错误报文返回码或者农行ERP应答错误报文返回来源
    				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
    				result.setErrorMsg(res.getRespInfo());
    				result.setSuccess(false);
                }else {
                	result.setBankRetCode(res.getRespCode());
                	result.setErrorMsg(res.getRespInfo());
    				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
    				result.setSuccess(false);
    			}

			return result;
		} catch (GopayException e) {
			logger.error("ABC银企直连异常 query bal", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception ex){
			logger.error("ABC银企直连异常 query bal error", ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}
	
	@Override
	public BcdlResult sendBank(BcdlMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BcdlResult sendBankQueryBalance(BcdlMessage base) {
		// TODO Auto-generated method stub
		return null;
	}
	
	

    @Override
	public BcdlResult eftRetry(BcdlMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public BcdlResult sendBankPacket(BcdlPacket bcdlPacket) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BcdlPacketRes queryPacket(BcdlPacket bcdlPacket) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BcdlResult queryAcctDetail(BcdlMessage base) {
		BcdlResult result = new BcdlResult();
		ApResCQRA10 res=null;
		try {
			BcdlMessage message = (BcdlMessage) base;
			message.setDcblType(BankConstants.DCBL_QUERY);
			 res = abcBcdlManager.queryAcctDetail(message);
			result.setDefaultModel(res);
			if(AbcConstants.ABC_RESCODE_SUCCESS.equals(res.getRespcode())){
				// 银行请求成功
				result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
				result.setSuccess(true);
//				result.setModel("payAccNum", res.getPayAccNum());
			}else if(!AbcConstants.ABC_ERP_ERR_RES_RESP_CODE.equals("") ){
				//  农行ERP应答错误报文返回码或者农行ERP应答错误报文返回来源
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
				result.setErrorMsg(res.getRespinfo());
				result.setSuccess(false);
			}else {
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
				result.setSuccess(false);
			}

			return result;
		} catch (GopayException e) {
			logger.error("ABC银企直连异常 queryAcctDetail", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception ex){
			logger.error("ABC银企直连异常 queryAcctDetail error", ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}
}
